package com.example.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.example.generator.config.GeneratorConfiguration;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collections;

/**
 * <p>
 *
 * </p>
 *
 * @author zhouchang
 */
@AllArgsConstructor
@Component
public class Generator {

    private GeneratorConfiguration configuration;

    public void generator() {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + this.configuration.getModule();

        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(this.configuration.getAuthor());
        gc.setOpen(false);

        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName(this.configuration.getMapperName());
        gc.setXmlName(this.configuration.getXmlName());
        gc.setServiceName(this.configuration.getServiceName());
        gc.setServiceImplName(this.configuration.getServiceImplName());
        gc.setControllerName(this.configuration.getControllerName());
        gc.setIdType(IdType.AUTO);
        gc.setDateType(DateType.TIME_PACK);

        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);

        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setUrl(this.configuration.getUrl());
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(this.configuration.getUsername());
        dsc.setPassword(this.configuration.getPassword());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent(this.configuration.getParentPackage());
        pc.setController(this.configuration.getControllerPackageName());
        pc.setEntity(this.configuration.getEntityPackageName());
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
                /*Map<String,Object> map = new HashMap<>();
                map.put("pojoPackage","com.jgdt.cowell.mm.live.pojo." + module);
                map.put("parent",PARENT);
                this.setMap(map);*/
            }
        };

        //解决 mybatis generator 自身的BUG（此BUG导致xml文件无法放在指定的目录下）
        FileOutConfig mapper = new FileOutConfig("/templates/mapper.xml.vm") {
            // 自定义输出文件目录
            @Override
            public String outputFile(TableInfo tableInfo) {
                String parentPackage = configuration.getParentPackage();
                String path = configuration.getModule();
                if(StringUtils.hasText(parentPackage)){
                    path = parentPackage.replaceAll("\\.", "/");
                }
                return projectPath + "/src/main/java/" + path + "/mapper/xml/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        };

        /*FileOutConfig converter = new FileOutConfig("/templates/converter.java.vm") {
            // 自定义输出文件目录
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/java/com/jgdt/cowell/mm/live/"+module+"/util/"
                        + tableInfo.getEntityName() + "Converter" + StringPool.DOT_JAVA;
            }
        };

        // 这两个是输出到 另一个模块中，略有不同
        FileOutConfig dto = new FileOutConfig("/templates/dto.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return System.getProperty("user.dir") + "/mm-live-pojo/src/main/java/com/jgdt/cowell/mm/live/pojo/"
                        + module + "/" + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
            }
        };

        FileOutConfig vo = new FileOutConfig("/templates/vo.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return System.getProperty("user.dir") + "/mm-live-pojo/src/main/java/com/jgdt/cowell/mm/live/pojo/"
                        + module + "/" + tableInfo.getEntityName() + "VO" + StringPool.DOT_JAVA;
            }
        };*/



        cfg.setFileOutConfigList(Collections.<FileOutConfig>singletonList(mapper));

        // 如果模板引擎是 freemarker
        //String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        //String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        //List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        /*focList.add(new FileOutConfig() {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });*/
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        //cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        if(StringUtils.hasText(this.configuration.getControllerTemplate())){
            templateConfig.setController(this.configuration.getControllerTemplate());
        }

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
        strategy.setEntityLombokModel(this.configuration.isEnableLombokModel());
        strategy.setRestControllerStyle(true);
        //strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        strategy.setInclude(this.configuration.getTableNames().split(","));
        //strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(this.configuration.getTablePrefix() + "_");
        strategy.setEntityTableFieldAnnotationEnable(true);
        // 逻辑删除字段名
        if(StringUtils.hasText(this.configuration.getLogicDeleteName())){
            strategy.setLogicDeleteFieldName("deleted");
        }
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        mpg.execute();
    }

}
